package com.bds.tjj.service;

import java.net.URLDecoder;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import com.bds.tjj.model.QuarterAreaData;
import org.nutz.dao.Cnd;
import org.nutz.dao.impl.NutDao;
import org.springframework.stereotype.Service;

import com.bds.tjj.model.PropIndex;
import com.bds.tjj.model.QuarterData;
import com.bds.tjj.utils.Const;

/**
 * Created by guoyu on 2018/2/28.
 */
@Service
public class QuarterSumService {
    private static final org.apache.log4j.Logger LOGGER = org.apache.log4j.Logger.getLogger(QuarterSumService.class);
    private static final DecimalFormat df = new DecimalFormat("#.0");

    @Resource
    private NutDao dao;
    @Resource
    private UserService userService;

    public QuarterData getQuarterNum(String type) throws Exception {
        type = URLDecoder.decode(type, "utf-8");
        List<QuarterData> yearDataList = dao.query(QuarterData.class,
                Cnd.where("prop", "=", type).and("data", "is not", null).and("data", "<>", "").limit(1, 2).orderBy("yq", "desc"));
        if (yearDataList.size() > 0) {
            QuarterData quarterData = yearDataList.get(0);
            QuarterData quarterDataAgo = yearDataList.get(1);

            if (quarterData.getData() != null && quarterData.getData().contains(".")) {
                if (quarterData.getData().split("\\.")[1].length() > Const.decimal_num) {
                    quarterData.setData(df.format(Double.parseDouble(quarterData.getData())));
                }
            }

            // 计算增长率
            try {
                if (quarterData.getYq() - quarterDataAgo.getYq() == 3) {
                    if (quarterData.getData() != null && (!quarterData.getData().equals(""))) {
                        double a = Double.parseDouble(quarterData.getData())
                                - Double.parseDouble(quarterDataAgo.getData());
                        double b = Math.abs(Double.parseDouble(quarterDataAgo.getData()));
                        double r = (a * 1.0 / b) * 100;
                        quarterData.setYya(Double.parseDouble(df.format(r)));
                        quarterData.setAbs(Double.parseDouble(df.format(a)));
                    } else {
                        quarterData.setYya(null);
                        quarterData.setAbs(null);
                    }
                } else {
                    quarterData.setYya(null);
                    quarterData.setAbs(null);
                }
            } catch (Exception e) {
                quarterData.setYya(null);
                quarterData.setAbs(null);
            }
            return quarterData;
        } else {
            return new QuarterData();
        }

    }

    public QuarterData getLastQuar() throws Exception {

        List<QuarterData> ls = dao.query(QuarterData.class, Cnd.NEW().limit(1, 1).desc("yq"));
        if (ls != null && ls.size() > 0) {
            return ls.get(0);
        } else {
            return null;
        }
    }

    public List<QuarterData> getQuarTips() throws Exception {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DAY_OF_MONTH, -7);
        Date lastdate = cal.getTime();
        List<PropIndex> ps = userService.getDataSelect("quarter");
        List<QuarterData> ys = new ArrayList<QuarterData>();
        for (int i = 0; i < ps.size(); i++) {
            PropIndex pi = ps.get(i);
            QuarterData yy = this.getQuarterNum(pi.getProp());
            if (yy != null) {
                if (yy.getCreate_time().after(lastdate)) {
                    yy.setIsnew("1");
                } else {
                    yy.setIsnew("0");
                }
                if (i % 4 == 0) {
                    yy.setStyle_class("success");
                } else if (i % 4 == 1) {
                    yy.setStyle_class("info");
                } else if (i % 4 == 2) {
                    yy.setStyle_class("important");
                } else if (i % 4 == 3) {
                    yy.setStyle_class("warning");
                }
                ys.add(yy);
            } else {
                LOGGER.error("没有此指标:" + pi.getCn_name());
            }

        }

        return ys;

    }

    public List<QuarterData> getQuarTips(String tabName) throws Exception {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DAY_OF_MONTH, -7);
        Date lastdate = cal.getTime();
        List<PropIndex> ps = userService.getDataSelect("quarter", tabName);
        List<QuarterData> ys = new ArrayList<QuarterData>();
        for (int i = 0; i < ps.size(); i++) {
            PropIndex pi = ps.get(i);
            if (pi.getIs_area() == 1) {
                continue;
            }
            QuarterData yy = this.getQuarterNum(pi.getProp());

            yy.setUnit(pi.getUnit());
            yy.setYq_name(transToQuarter(yy.getYq() + ""));

            if (yy != null) {
                if (yy.getCreate_time().after(lastdate)) {
                    yy.setIsnew("1");
                } else {
                    yy.setIsnew("0");
                }
                yy.setEn_name(pi.getView_name());
                if (i % 4 == 0) {
                    yy.setStyle_class("success");
                } else if (i % 4 == 1) {
                    yy.setStyle_class("info");
                } else if (i % 4 == 2) {
                    yy.setStyle_class("important");
                } else if (i % 4 == 3) {
                    yy.setStyle_class("warning");
                }
                ys.add(yy);
            } else {
                LOGGER.error("没有此指标:" + pi.getCn_name());
            }

        }

        return ys;

    }

    public List<QuarterData> getQuarterTrend(String type, int startTime, int endTime) throws Exception {
        type = URLDecoder.decode(type, "utf-8");
        List<QuarterData> list = dao.query(QuarterData.class,
                Cnd.where("prop", "=", type).and("yq", ">=", startTime).and("yq", "<=", endTime).orderBy("yq", "desc"));

        Collections.reverse(list);

        PropIndex prop = new PropIndex();
        if (list.size() > 0) {
            prop = dao.fetch(PropIndex.class, Cnd.where("prop", "=", list.get(0).getProp()));
        }

        String preData = null;
        for (int i = 0; i < list.size(); i++) {
            QuarterData quarterData = list.get(i);

            quarterData.setUnit(prop.getUnit());
            quarterData.setView_name(prop.getView_name());

            quarterData.setYq_name(transToQuarter(quarterData.getYq() + ""));

            // 需要计算增长率时才去计算
            if (prop.getIf_rate() == 0) {
                if (i == 0) {
                    quarterData.setYya(0.0);
                } else {
                    if (preData != null && (!preData.equals(""))) {
                        if (quarterData.getData() != null && (!quarterData.getData().equals(""))) {
                            double a = Double.parseDouble(quarterData.getData()) - Double.parseDouble(preData);
                            double b = Math.abs(Double.parseDouble(preData));
                            double r = (a * 1.0 / b) * 100;
                            quarterData.setYya(Double.parseDouble(df.format(r)));
                        }
                    } else {
                        quarterData.setYya(0.0);
                    }
                }
            }

            if (quarterData.getData() == null) {
                continue;
            }

            if (prop != null) {
                quarterData.setEn_name(prop.getEn_name());
                quarterData.setIs_area(prop.getIs_area());
            }
            // 是否是小数
            if (quarterData.getData().contains(".")) {
                // 小数点后是否大于4位
                if (quarterData.getData().split("\\.")[1].length() > Const.decimal_num) {
                    quarterData.setData(df.format(Double.parseDouble(quarterData.getData())));
                }
            }

            if (quarterData.getData() != null) {
                if (!quarterData.getData().equals("")) {
                    preData = quarterData.getData();
                }
            }
        }

        Collections.reverse(list);

        return list;
    }

    public List<QuarterAreaData> getQuarAreaTips(String tabName, String areaId) throws Exception {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DAY_OF_MONTH, -7);
        Date lastdate = cal.getTime();
        List<PropIndex> ps = userService.getDataAreaSelect("quarter", tabName);
        List<QuarterAreaData> ys = new ArrayList<QuarterAreaData>();
        for (int i = 0; i < ps.size(); i++) {
            PropIndex pi = ps.get(i);
            QuarterAreaData yy = this.getQuarterAreaNum(pi.getProp(), areaId);

            yy.setUnit(pi.getUnit());
            yy.setYq_name(transToQuarter(yy.getYq() + ""));

            if (yy != null) {
                if (yy.getCreate_time().after(lastdate)) {
                    yy.setIsnew("1");
                } else {
                    yy.setIsnew("0");
                }
                yy.setEn_name(pi.getView_name());
                if (i % 4 == 0) {
                    yy.setStyle_class("success");
                } else if (i % 4 == 1) {
                    yy.setStyle_class("info");
                } else if (i % 4 == 2) {
                    yy.setStyle_class("important");
                } else if (i % 4 == 3) {
                    yy.setStyle_class("warning");
                }
                ys.add(yy);
            } else {
                LOGGER.error("没有此指标:" + pi.getCn_name());
            }

        }

        return ys;

    }

    public List<QuarterAreaData> getQuarterAreaTrend(String type, int startTime, int endTime, String areaId) throws Exception {
        type = URLDecoder.decode(type, "utf-8");
        List<QuarterAreaData> list = dao.query(QuarterAreaData.class,
                Cnd.where("prop", "=", type)
                        .and("yq", ">=", startTime).and("yq", "<=", endTime)
                        .and("area_code", "=", areaId)
                        .orderBy("yq", "desc"));

        Collections.reverse(list);

        PropIndex prop = new PropIndex();
        if (list.size() > 0) {
            prop = dao.fetch(PropIndex.class, Cnd.where("prop", "=", list.get(0).getProp()));
        }

        String preData = null;
        for (int i = 0; i < list.size(); i++) {
            QuarterAreaData quarterAreaData = list.get(i);

            quarterAreaData.setUnit(prop.getUnit());
            quarterAreaData.setView_name(prop.getView_name());

            quarterAreaData.setYq_name(transToQuarter(quarterAreaData.getYq() + ""));

            // 需要计算增长率时才去计算
            if (prop.getIf_rate() == 0) {
                if (i == 0) {
                    quarterAreaData.setYya(0.0);
                } else {
                    if (preData != null && (!preData.equals(""))) {
                        if (quarterAreaData.getData() != null && (!quarterAreaData.getData().equals(""))) {
                            double a = Double.parseDouble(quarterAreaData.getData()) - Double.parseDouble(preData);
                            double b = Math.abs(Double.parseDouble(preData));
                            double r = (a * 1.0 / b) * 100;
                            quarterAreaData.setYya(Double.parseDouble(df.format(r)));
                        }
                    } else {
                        quarterAreaData.setYya(0.0);
                    }
                }
            }

            if (quarterAreaData.getData() == null) {
                continue;
            }

            if (prop != null) {
                quarterAreaData.setEn_name(prop.getEn_name());
                quarterAreaData.setIs_area(1);
            }
            // 是否是小数
            if (quarterAreaData.getData().contains(".")) {
                // 小数点后是否大于4位
                if (quarterAreaData.getData().split("\\.")[1].length() > Const.decimal_num) {
                    quarterAreaData.setData(df.format(Double.parseDouble(quarterAreaData.getData())));
                }
            }

            if (quarterAreaData.getData() != null) {
                if (!quarterAreaData.getData().equals("")) {
                    preData = quarterAreaData.getData();
                }
            }
        }

        Collections.reverse(list);

        return list;
    }

    public QuarterAreaData getQuarterAreaNum(String type, String areaId) throws Exception {
        type = URLDecoder.decode(type, "utf-8");
        List<QuarterAreaData> quarterAreaDataList = dao.query(QuarterAreaData.class,
                Cnd.where("prop", "=", type).and("data", "is not", null)
                        .and("data", "<>", "").and("area_code", "=", areaId)
                        .limit(1, 2).orderBy("yq", "desc"));
        if (quarterAreaDataList.size() > 0) {
            QuarterAreaData quarterData = quarterAreaDataList.get(0);
            QuarterAreaData quarterDataAgo = quarterAreaDataList.get(1);

            if (quarterData.getData() != null && quarterData.getData().contains(".")) {
                if (quarterData.getData().split("\\.")[1].length() > Const.decimal_num) {
                    quarterData.setData(df.format(Double.parseDouble(quarterData.getData())));
                }
            }

            // 计算增长率
            try {
                if (quarterData.getYq() - quarterDataAgo.getYq() == 3) {
                    if (quarterData.getData() != null && (!quarterData.getData().equals(""))) {
                        double a = Double.parseDouble(quarterData.getData())
                                - Double.parseDouble(quarterDataAgo.getData());
                        double b = Math.abs(Double.parseDouble(quarterDataAgo.getData()));
                        double r = (a * 1.0 / b) * 100;
                        quarterData.setYya(Double.parseDouble(df.format(r)));
                    } else {
                        quarterData.setYya(null);
                    }
                } else {
                    quarterData.setYya(null);
                }
            } catch (Exception e) {
                quarterData.setYya(null);
            }
            return quarterData;
        } else {
            return new QuarterAreaData();
        }

    }

    private String transToQuarter(String yq) {
        String yqName = yq.substring(4, 6);
        String yqPre = yq.substring(0, 4);

        if (yqName.equals("01")) {
            yqName = yqPre + "Q1";
        } else if (yqName.equals("04")) {
            yqName = yqPre + "Q2";
        } else if (yqName.equals("07")) {
            yqName = yqPre + "Q3";
        } else {
            yqName = yqPre + "Q4";
        }

        return yqName;
    }
}
